'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function oColorpiker(o) {

    colorPikerInit(o);
    function colorPikerInit(obj) {
        //onchangge方法传lastcolor颜色输出值
        var onchange = obj.onChange;
        //Dom 结构
        var str = '<div class="show-color-box"><div class="show-color" style="background-color: rgb(114, 50, 50);"></div></div>' + '<div class="colorpiker">' + '<div class="color-picker-style"><span class="color-picker-str">推荐色</span>' + '<ul class="color-picker-list">' + '<li class="color-picker-point" data="0"></li>' + '<li class="color-picker-point" data="1"></li>' + '<li class="color-picker-point color-add-style" data="2"></li>' + '<li class="color-picker-point" data="3"></li>' + '<li class="color-picker-point" data="4"></li>' + '<li class="color-picker-point" data="5"></li>' + '<li class="color-picker-point" data="6"></li>' + '<li class="color-picker-point" data="7"></li>' + '</ul>' + '</div>' + '<div class="left-palette">' + '<div class="left-palette-white"></div>' + '<div class="left-palette-black">' + '<div class="color-picker-getpoint "></div>' + '</div>' + '</div>' + '<div class="right-palette">' + '<div class="rule color-piker-rule"></div>' + '</div>' + '<div class="rgb-inner color-piker-rgb-inner">#5991FF</div>' + '<div class="color-cancel color-piker-cancel">取消</div>' + '<div class="color-submit color-piker-submit">确认</div>' + '</div>';
        //实列对象传入的容器元素
        var contentEl = obj.el.split('#')[1];

        //颜色拾取器容器Dom元素
        var color_picker_box = document.getElementById(contentEl);

        //颜色拾取器容器元素添加类名
        color_picker_box.className = 'rwly-color-picker';

        //颜色拾取器容器元素添加Dom结构
        color_picker_box.innerHTML = str;

        //推荐色,样式选择顶部盒子
        var color_picker_list = slt(color_picker_box, 'color-picker-list');

        //颜色拾取区(左)
        var left_palette = slt(color_picker_box, 'left-palette');

        //元素抓取图标(小圆圈)
        var color_picker_getpoint = slt(color_picker_box, 'color-picker-getpoint');

        //右颜色维度拖拽条
        var palette_rule = slt(color_picker_box, 'color-piker-rule');

        //左下文字展示区盒子
        var rgbInner = slt(color_picker_box, 'color-piker-rgb-inner');

        //取消
        var color_cancel = slt(color_picker_box, 'color-piker-cancel');

        //确认
        var color_submit = slt(color_picker_box, 'color-piker-submit');

        //顶部显示隐藏切换按钮
        var show_color_box = slt(color_picker_box, 'show-color-box');
        var triggerElTag = obj.triggerEl.split('#')[1];
        show_color_box.setAttribute('id', triggerElTag);

        //顶部显示隐藏切换按钮内部样式盒子
        var showColor = slt(color_picker_box, 'show-color');

        //底部颜色操作区父盒子
        var colorpiker = slt(color_picker_box, 'colorpiker');

        //顶部ul
        var color_picker_list = slt(colorpiker, 'color-picker-list');

        //顶部ul中li数组(风格切换圆点)
        var lists = color_picker_list.querySelectorAll('.color-picker-point');

        //颜色输出值
        var show_color_box;

        //右边颜色起始值
        var right_color = [255, 0, 0];

        //最终颜色输出值
        var last_color = '';

        //显示隐藏开关
        var flag = true;
        
        //空数组
        var xSelectColor = [];

        //showColor隐藏显示盒子传入样式
        showColor.style.backgroundColor = obj.default;

        //样式init
        switch (obj.default) {
            case '#3598DB':
                getXYT('#3598DB', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('0', obj.default, lists, rgbInner);
                break;
            case '#F5A623':
                getXYT('#F5A623', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('1', obj.default, lists, rgbInner);
                break;
            case '#5991FF':
                getXYT('#5991FF', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('2', obj.default, lists, rgbInner);
                break;
            case '#78D140':
                getXYT('#78D140', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('3', obj.default, lists, rgbInner);
                break;
            case '#FD6654':
                getXYT('#FD6654', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('4', obj.default, lists, rgbInner);
                break;
            case '#5AC8FA':
                getXYT('#5AC8FA', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('5', obj.default, lists, rgbInner);
                break;
            case '#15D0BD':
                getXYT('#15D0BD', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('6', obj.default, lists, rgbInner);
                break;
            case '#5856D6':
                getXYT('#5856D6', palette_rule, color_picker_getpoint, left_palette);
                getPositionDefault('7', obj.default, lists, rgbInner);
                break;
        }


        // rgb转hex
        function colorRGB2Hex(color) {
            var r = color[0];
            var g = color[1];
            var b = color[2];
            var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
            return hex.toUpperCase();
        }
        //hex转rgb
        function hexToRgba(hex) {
            return parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt("0x" + hex.slice(5, 7));
        }

        //show_color_box点击显示和隐藏
        show_color_box.addEventListener('click', function (e) {
            if (flag) {
                colorpiker.style.cssText = 'opacity:1;display:block';
                flag = false;
            } else {
                colorpiker.style.cssText = 'opacity:0;display:none';
                flag = true;
            }
        }, false);

        //顶部8个圆点点击事件(li标签)
        color_picker_list.addEventListener('click', function (e) {
            //圆点样式切换
            lists.forEach(function (item, index) {
                item.setAttribute('data', index);
                item.classList.remove('color-add-style');
                if (e.target.className.indexOf('color-picker-point') !== -1) {
                    e.target.classList.add('color-add-style');
                }
            });
            //根据圆点li颜色进行左X,Y 右TOP的定位
            switch (e.target.getAttribute('data')) {
                case '0':
                    getXYT('#3598DB', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#3598DB', showColor, rgbInner);
                    break;
                case '1':
                    getXYT('#F5A623', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#F5A623', showColor, rgbInner);
                    break;
                case '2':
                    getXYT('#5991FF', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#5991FF', showColor, rgbInner);
                    break;
                case '3':
                    getXYT('#78D140', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#78D140', showColor, rgbInner);
                    break;
                case '4':
                    getXYT('#FD6654', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#FD6654', showColor, rgbInner);
                    break;
                case '5':
                    getXYT('#5AC8FA', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#5AC8FA', showColor, rgbInner);
                    break;
                case '6':
                    getXYT('#15D0BD', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#15D0BD', showColor, rgbInner);
                    break;
                case '7':
                    getXYT('#5856D6', palette_rule, color_picker_getpoint, left_palette);
                    getColorwz('#5856D6', showColor, rgbInner);
                    break;
            }
        }, true);

        //确认按钮获取颜色最终值last_color
        color_submit.addEventListener('click', function (e) {
            flag = true;
            colorpiker.style.cssText = 'display:none';
            var cc = rgbInner.innerText;
            last_color = cc;
            showColor.style.backgroundColor = last_color;
            //给实列对象传入颜色最后输出值
            onchange(last_color);
        }, false);

        //取消按钮回到样式初始值
        color_cancel.addEventListener('click', function () {
            flag = true;
            colorpiker.style.cssText = 'display:none';
            showColor.style.backgroundColor = obj.default;
            lists.forEach(function (item, index) {
                item.setAttribute('data', index);
                item.classList.remove('color-add-style');
                if (item.getAttribute('data') === '2') {
                    item.classList.add('color-add-style');
                }
            });
        }, false);


        //获取右边色盘RGB输出值
        palette_rule.addEventListener('mousedown', function (e) {
            //起始Y
            var startY = e.pageY;
            //偏移值
            var top = palette_rule.offsetTop;

            //添加move事件监听
            document.body.addEventListener('mousemove', mouseMovEven);
            //获取右边颜色输出值方法
            function mouseMovEven(event) {
                var y = event.pageY - startY + top;
                y = y > 162 ? 162 : y < 0 ? 1 : y;
                if (y > 160) {
                    return;
                };
                palette_rule.style.top = y + 'px';
                var scaler = Math.ceil(y / 27);
                var color = Math.abs(Math.ceil(255 - (scaler * 30 - y + 1) * (255 / 30)));
                switch (scaler) {
                    case 0:
                        right_color = [255, color, 0];
                        break;
                    case 1:
                        right_color = [255, color, 0];
                        break;
                    case 2:
                        right_color = [Math.abs(255 - color), 255, 0];
                        break;
                    case 3:
                        right_color = [0, 255, color];
                        break;
                    case 4:
                        right_color = [0, Math.abs(255 - color), 255];
                        break;
                    case 5:
                        right_color = [color, 0, 255];
                        break;
                    case 6:
                        right_color = [255, 0, Math.abs(255 - color)];
                        break;
                    default:
                        right_color = [255, color, 0];
                        break;
                }
                //left盒子添加左边获得的颜色
                left_palette.style.backgroundColor = 'rgb(' + right_color.join(',') + ')';
                //根据颜色抓取圆点坐标改变样式和颜色显示字符
                xSelectColor = right_color.map(function (val, index) {
                    var w = parseInt(color_picker_getpoint.style.left.split('px')[0]);
                    var wStep = (val - 255) / 242;
                    var wVal = 255 + w * wStep;
                    var h = parseInt(color_picker_getpoint.style.top.split('px')[0]);
                    var hStep = (0 - wVal) / 160;
                    var hVal = wVal + h * hStep;
                    return parseInt(hVal);
                });
    
                // 左边获取的颜色值RGB格式转hex格式
                var colorStr = colorRGB2Hex(xSelectColor);
                setStyle(showColor, 'background-color:' + colorStr);
                rgbInner.innerHTML = colorStr;

            }

            document.body.addEventListener('mouseup', function () {
                document.body.removeEventListener('mousemove', mouseMovEven, false);
            });
        });

        //左边选色根据鼠标X,Y获取颜色值
        function getcolor(e) {
            // console.log(right_color)
            xSelectColor = right_color.map(function (val, index) {
                var w = e.offsetX;
                var wStep = (val - 255) / 242;
                var wVal = 255 + w * wStep;
                var h = e.offsetY;
                var hStep = (0 - wVal) / 160;
                var hVal = wVal + h * hStep;
                setStyle(color_picker_getpoint, 'top:' + h + 'px; left:' + w + 'px');
                return parseInt(hVal);
            });

            //左边获取的颜色值RGB格式转hex格式
            var colorStr = colorRGB2Hex(xSelectColor);
            setStyle(showColor, 'background-color:' + colorStr);
            rgbInner.innerHTML = colorStr;
        }

        //左边颜色拾取区鼠标点击和拖拽事件
        left_palette.addEventListener('mousedown', function (e) {
            getcolor(e);
            left_palette.addEventListener('mousemove', getcolor);
            left_palette.addEventListener('mouseup', function (e) {
                getcolor(e);
                left_palette.removeEventListener('mousemove', getcolor);
            });
        }, true);

        //query元素类名
        function slt(p, s) {
            return p.querySelector('.' + s);
        }

        //设置元素style
        function setStyle(el, str) {
            el.style.cssText += str;
        }

        //根据li得id 设置样式
        function getPositionDefault(id, color, lists, rgbInner) {
            lists.forEach(function (item, index) {
                item.classList.remove('color-add-style');
                item.getAttribute('data') === id ? item.classList.add('color-add-style') : '';
                rgbInner.innerHTML = color;
            });
        }

        //根据默认设置设置样式
        function getColorwz(c, showColor, rgbInner) {
            rgbInner.innerHTML = c;
            showColor.style.backgroundColor = c;
        }



        ///颜色反推坐标-------------------------------------


        //hex转hsl
        function rgbToHsb(hex) {
            var hsb = { h: 0, s: 0, b: 0 };
            if (hex.indexOf('#') === 0) {
                hex = hex.substring(1);
            }
            if (hex.length === 3) {
                hex = hex.split('').join('');
            }
            if (hex.length !== 6) {
                return false;
            }
            hex = [hex.substr(0, 2), hex.substr(2, 2), hex.substr(4, 2)].map(function (s) {
                return parseInt(s, 16);
            });
            var rgb = {
                r: hex[0],
                g: hex[1],
                b: hex[2]
            };
            var MAX = Math.max.apply(Math, _toConsumableArray(hex));
            var MIN = Math.min.apply(Math, _toConsumableArray(hex));

            if (MAX === MIN) {
                hsb.h = 0;
            } else if (MAX === rgb.r && rgb.g >= rgb.b) {
                hsb.h = 60 * (rgb.g - rgb.b) / (MAX - MIN) + 0;
            } else if (MAX === rgb.r && rgb.g < rgb.b) {
                hsb.h = 60 * (rgb.g - rgb.b) / (MAX - MIN) + 360;
            } else if (MAX === rgb.g) {
                hsb.h = 60 * (rgb.b - rgb.r) / (MAX - MIN) + 120;
            } else if (MAX === rgb.b) {
                hsb.h = 60 * (rgb.r - rgb.g) / (MAX - MIN) + 240;
            }

            if (MAX === 0) {
                hsb.s = 0;
            } else {
                hsb.s = 1 - MIN / MAX;
            }
            hsb.b = MAX / 255;
            return hsb;
        }
        //hsl转rgb
        function HSV2RGB (h, s, v) {
            var r, g, b, i, f, p, q, t
            
            i = Math.floor(h * 6)
            f = h * 6 - i
            p = v * (1 - s)
            q = v * (1 - f * s)
            t = v * (1 - (1 - f) * s)
            i = i || 0
            q = q || 0
            t = t || 0
            switch (i % 6) {
              case 0:
                  r = v, g = t, b = p
                  break
              case 1:
                  r = q, g = v, b = p
                  break
              case 2:
                  r = p, g = v, b = t
                  break
              case 3:
                  r = p, g = q, b = v
                  break
              case 4:
                  r = t, g = p, b = v;
                  break;
              case 5:
                  r = v, g = p, b = q
                  break
            }
            return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
          }
          


        //根据HSL颜色值反推坐标X,Y值 和右边盒子top值
        function getXYT(hex, palette_rule, color_picker_getpoint, left_palette) {
            //根据Hsb值获取左边拖拽条高度
            var leftTop = rgbToHsb(hex).h * 162 / 360;
            //改变左边拖拽条高度
            palette_rule.style.top = Math.abs(parseInt(leftTop) - 14) + 'px';
            //根据hex给Hsl的s和b赋值
            var s = rgbToHsb(hex).s;
            var b = rgbToHsb(hex).b;
            var y = leftTop;
            y = y > 162 ? 162 : y < 0 ? 1 : y;
            if (y > 160) {
                return;
            };
            palette_rule.style.top = y + 'px';
            var scaler = Math.ceil(y / 27);
            var color = Math.abs(Math.ceil(255 - (scaler * 30 - y + 1) * (255 / 30)));
            switch (scaler) {
                case 0:
                    right_color = [255, color, 0];
                    break;
                case 1:
                    right_color = [255, color, 0];
                    break;
                case 2:
                    right_color = [Math.abs(255 - color), 255, 0];
                    break;
                case 3:
                    right_color = [0, 255, color];
                    break;
                case 4:
                    right_color = [0, Math.abs(255 - color), 255];
                    break;
                case 5:
                    right_color = [color, 0, 255];
                    break;
                case 6:
                    right_color = [255, 0, Math.abs(255 - color)];
                    break;
                default:
                    right_color = [255, color, 0];
                    break;
            }

            left_palette.style.backgroundColor = 'rgb(' + right_color.join(',') + ')';

            if (b >= 0.5) {
                color_picker_getpoint.style.left = parseInt(242 - (1 - b) * 242 / 0.5 - 10) + 'px';
                color_picker_getpoint.style.top = parseInt(163 - b * 162) + 'px';
            } else {
                color_picker_getpoint.style.left = b * 242 + 'px';
                color_picker_getpoint.style.top = 162 - 162 * b / 0.5 + 'px';
            }
        }


        ///未解决bug 1.颜色闪烁 2.右边拖动滑动条时 左边颜色显示文字不变
    }
}